import config from "@/config"
import { tansParams, toast } from "@/utils/common"

let timeout = 10000
const baseUrl = config.baseUrl

const request = config => {
	console.log("发起请求:", config.url)
	console.log("完整URL:", config.baseUrl || baseUrl + config.url)
	console.log("请求配置:", config)
	// 是否需要设置 token

	// get请求映射params参数
	if (config.params) {
		let url = config.url + "?" + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	return new Promise((resolve, reject) => {
		console.log("进入promise")

		uni.request({
			method: config.method || "get",
			timeout: config.timeout || timeout,
			url: config.baseUrl || baseUrl + config.url,
			data: config.data,
			header: config.header,
			dataType: "json",
		})
			.then(response => {
				console.log(response, "response")

				const res = response
				console.log(res, "res")
				if (res.data.code == 200) {
					resolve(res.data)
				} else {
					reject(res.data.message)
				}
			})
			.catch(error => {
				let { message } = error
				if (message === "Network Error") {
					message = "后端接口连接异常"
				} else if (message?.includes("timeout")) {
					message = "系统接口请求超时"
				} else if (message.includes("Request failed with status code")) {
					message = "系统接口" + message.substr(message.length - 3) + "异常"
				}
				toast(message)
				reject(error)
			})
	})
}

export default request
